package org.wannatrak.android.service;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import org.wannatrak.android.ApplicationContext;
import org.wannatrak.android.entity.BaseEntity;
import org.wannatrak.android.entity.TrackHistory;

/**
 * @Author: Maksim Tulupov maxtulupov@gmail.com
 * @Date: $Date: 2011-11-29 08:41:22 +0000 (Tue, 29 Nov 2011) $ 11:02 AM
 * @version: $Revision: 33 $
 * @id: $Id: TrackHistoryService.java 33 2011-11-29 08:41:22Z maxtulupov@gmail.com $
 */
public class TrackHistoryService {

    private Context context;

    private final int MAX_HISTORY_SIZE = 10;

    public TrackHistoryService(Context context) {
        this.context = context;
    }

    public boolean isHistoryEmpty() {
        Cursor c = null;
        try {
            c = ApplicationContext.getDatabaseHelper().executeRawSQL("select count(1) as " + BaseEntity._COUNT
                    + " from " + TrackHistory.CONTENT_DIRECTORY, null);
            if (c.moveToFirst()) {
                return c.getInt(c.getColumnIndex(BaseEntity._COUNT)) <= 0;
            }
            return true;
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    public void deleteFromHistory(String name) {
        context.getContentResolver().delete(TrackHistory.CONTENT_URI, TrackHistory.NAME + " = ?",
                new String[] {name});
    }

    public void clearHistory() {
        context.getContentResolver().delete(TrackHistory.CONTENT_URI, null, null);
    }

    public void putInHistory(String name, String sendInterval, String saveInterval, String trackId) {
        try {
            long currentValue = ApplicationContext.getTrackCounterService().getCurrentValue();
            long historyPosition = 1L;
            if (currentValue > 0) {
                historyPosition = currentValue % MAX_HISTORY_SIZE;
            }
            long inDbById = ApplicationContext.getCommonService().isEntityExistInDbById(TrackHistory.CONTENT_URI, historyPosition);
            ContentValues cv = new ContentValues();
            cv.put(TrackHistory.CREATE_DATE, System.currentTimeMillis());
            cv.put(TrackHistory.NAME, name);
            cv.put(TrackHistory.SEND_INTERVAL, sendInterval);
            cv.put(TrackHistory.SAVE_INTERVAL, saveInterval);
            cv.put(TrackHistory.TRACK_ID, trackId);
            if (inDbById > 0) {
                context.getContentResolver().update(TrackHistory.CONTENT_URI, cv, BaseEntity._ID + " = ?",
                        new String[]{String.valueOf(inDbById)});
            } else {
                context.getContentResolver().insert(TrackHistory.CONTENT_URI, cv);
            }
            ApplicationContext.getTrackCounterService().incValue();
        } catch (Exception e) {
            //Do nothing
        }
    }
}
